<template>
	<view class="scrool-page">
		<view class="list-cont">
			<scroll-view class="scrool-more" style="height: 100%" scroll-y="true" scroll-with-animation="true">
				<view v-for="(item,index) in productList">
					<uni-card :title="'产成品序号:'+(index+1)" v-if='!item.flag'>
						<text class="uni-body">物料编码：{{ item.code }}</text><br>
						<text class="uni-body">数量：{{ item.codeEqualQty }}</text><br>
						<text class="uni-body">箱码：{{ item.boxCode }}</text><br>
					</uni-card>

					<uni-card :title="'产成品序号:'+(index+1)" v-else style='background-color: darkgrey;'>
						<text class="uni-body">物料编码：{{ item.code }}</text><br>
						<text class="uni-body">数量：{{ item.codeEqualQty }}</text><br>
						<text class="uni-body">箱码：{{ item.boxCode }}</text><br>
					</uni-card>
				</view>
			</scroll-view>
		</view>

		<view class="footer">
			<button type="default" size='mini' @click="reduceData" style="width:48%; margin-left:1%;"
				v-if="!userflag">减码</button>
			<button type="default" size='mini' @click="reduceData" style="width:48%; margin-left:1%;" v-else>加箱</button>
			<button type="default" size='mini' @click="submit" style="width:49%; margin-left:1%;">完成</button>
		</view>

		<uni-popup ref="alertDialog" type="dialog" :is-mask-click="false">
			<uni-popup-dialog type="success" cancelText="关闭" confirmText="确定" title="提示" :before-close="true"
				:content="content" @confirm="dialogConfirm" @close="dialogClose">
			</uni-popup-dialog>
		</uni-popup>

		<uni-popup ref="reduceDialog" type="dialog" :is-mask-click="false">
			<uni-popup-dialog type="success" cancelText="关闭" confirmText="确定" title="提示" :before-close="true"
				:content="reduceContent" @confirm="reduceConfirm" @close="reduceClose">
			</uni-popup-dialog>
		</uni-popup>

		<uni-popup ref="messageDialog" type="dialog" :is-mask-click="false">
			<uni-popup-dialog type="success" cancelText="关闭" confirmText="确定" title="提示" :before-close="true"
				:content="messageeContent" @confirm="messageConfirm" @close="messageClose">
			</uni-popup-dialog>
		</uni-popup>

		<uni-popup ref="dataDialog" type="dialog" :is-mask-click="false">
			<uni-popup-dialog type="success" cancelText="关闭" confirmText="确定" title="提示" :before-close="true"
				:content="dataContent" @confirm="dataConfirm" @close="dataClose">
			</uni-popup-dialog>
		</uni-popup>

		<uni-popup ref="commonDialog" type="dialog" :is-mask-click="false">
			<uni-popup-dialog type="success" cancelText="关闭" confirmText="确定" title="提示" :before-close="true"
				:content="commonContent" @confirm="commonConfirm" @close="commonClose">
			</uni-popup-dialog>
		</uni-popup>
	</view>

</template>

<script>
	import Vue from 'vue'
	import {
		getToken
	} from '@/utils/auth'
	import common from '../../pages/common/common.js'
	const printer = uni.requireNativePlugin('LcPrinter');
	const modal = uni.requireNativePlugin('modal');
	var globalEvent = uni.requireNativePlugin('globalEvent');

	function utf8ByteToUnicodeStr(utf8Bytes) {
		var unicodeStr = "";
		for (var pos = 0; pos < utf8Bytes.length;) {
			var flag = utf8Bytes[pos];
			var unicode = 0;
			if ((flag >>> 7) === 0) {
				unicodeStr += String.fromCharCode(utf8Bytes[pos]);
				pos += 1;

			} else if ((flag & 0xFC) === 0xFC) {
				unicode = (utf8Bytes[pos] & 0x3) << 30;
				unicode |= (utf8Bytes[pos + 1] & 0x3F) << 24;
				unicode |= (utf8Bytes[pos + 2] & 0x3F) << 18;
				unicode |= (utf8Bytes[pos + 3] & 0x3F) << 12;
				unicode |= (utf8Bytes[pos + 4] & 0x3F) << 6;
				unicode |= (utf8Bytes[pos + 5] & 0x3F);
				unicodeStr += String.fromCodePoint(unicode);
				pos += 6;

			} else if ((flag & 0xF8) === 0xF8) {
				unicode = (utf8Bytes[pos] & 0x7) << 24;
				unicode |= (utf8Bytes[pos + 1] & 0x3F) << 18;
				unicode |= (utf8Bytes[pos + 2] & 0x3F) << 12;
				unicode |= (utf8Bytes[pos + 3] & 0x3F) << 6;
				unicode |= (utf8Bytes[pos + 4] & 0x3F);
				unicodeStr += String.fromCodePoint(unicode);
				pos += 5;

			} else if ((flag & 0xF0) === 0xF0) {
				unicode = (utf8Bytes[pos] & 0xF) << 18;
				unicode |= (utf8Bytes[pos + 1] & 0x3F) << 12;
				unicode |= (utf8Bytes[pos + 2] & 0x3F) << 6;
				unicode |= (utf8Bytes[pos + 3] & 0x3F);
				unicodeStr += String.fromCodePoint(unicode);
				pos += 4;

			} else if ((flag & 0xE0) === 0xE0) {
				unicode = (utf8Bytes[pos] & 0x1F) << 12;;
				unicode |= (utf8Bytes[pos + 1] & 0x3F) << 6;
				unicode |= (utf8Bytes[pos + 2] & 0x3F);
				unicodeStr += String.fromCharCode(unicode);
				pos += 3;

			} else if ((flag & 0xC0) === 0xC0) { //110
				unicode = (utf8Bytes[pos] & 0x3F) << 6;
				unicode |= (utf8Bytes[pos + 1] & 0x3F);
				unicodeStr += String.fromCharCode(unicode);
				pos += 2;

			} else {
				unicodeStr += String.fromCharCode(utf8Bytes[pos]);
				pos += 1;
			}
		}
		return unicodeStr;
	}
	var main, receiver, filter;
	var ScanDeviceClass = plus.android.importClass("android.device.ScanDevice");
	var scanDevice;
	export default {
		data() {
			return {
				productList: [],
				list: [],
				content: '',
				code: '',
				codeEqualQty: '',
				boxCode: '',
				allCode: '',
				count: 0,
				userflag: false,
				codeStr: '',
				popFlag: false,
				reduceContent: '',
				reduceCode: '',
				reduceNumkber: '',
				reducePatch: '',
				reduceCount: 0,
				barcodeIdList: [],
				recordList: [],
				dataContent: '检测到有缓存数据是否加载？',
				messageeContent: '确认删除数据吗?',
				sumbitFlag: false,
				baseUrl: getApp().globalData.config.baseUrl,
				userName: this.$store.state.user.name,
				orgId: getApp().globalData.config.orgId,
				commonContent: '',
			}
		},

		onLoad: function() {
			this.orgId = uni.getStorageSync('orgId');
			// 添加打印状态监听
			globalEvent.addEventListener('onPrintCallback', function(e) {
				// uni.showToast({
				// 	title: 'state: ' + JSON.stringify(e),
				// 	duration: 2000
				// });
				if (e.key == 0) {
					console.log('product_repct', '打印成功');
					// uni.showToast({
					// 	title: '打印成功',
					// 	duration: 2000
					// });
				} else if (e.key == 3) {
					uni.showToast({
						title: '缺纸',
						duration: 2000
					});
				}
			});
			//打印机版本获取回调
			globalEvent.addEventListener('onVersion', function(e) {
				// uni.showToast({
				// 	title: 'version: ' + JSON.stringify(e),
				// 	duration: 2000
				// });
			});

			globalEvent.addEventListener('getsupportprint', function(e) {
				//console.log('key: ' + JSON.stringify(e));
				// uni.showToast({
				// 	title: 'key: ' + JSON.stringify(e),
				// 	duration: 2000
				// });
			});
		},

		onHide: function() {
			this.unregisterScan();
		},

		destroyed: function() {
			this.unregisterScan();
		},

		onShow() {
			scanDevice = new ScanDeviceClass();
			scanDevice.openScan(); // 打开扫描
			scanDevice.setOutScanMode(0); // 扫描模式		
			this.initScan();
			this.registerScan();
		},

		mounted() {
			var that = this;
			that.orgId = uni.getStorageSync('orgId');
			that.content = '';
			that.code = '';
			that.codeEqualQty = '';
			that.boxCode = '';
			that.count = 0;
			that.userflag = false;
			that.codeStr = '';
			that.popFlag = false;
			that.reduceContent = '';
			that.reduceCode = '';
			that.reduceNumkber = '';
			that.reducePatch = '';
			that.reduceCount = 0;
			const value = uni.getStorageSync('product_recpt');
			if (value.length > 0) {
				that.$refs.dataDialog.open();
			} else {
				that.list = [];
				that.productList = [];
				that.barcodeIdList = [];
			}

		},

		onBackPress(options) {
			var that = this;
			if (options.from === 'navigateBack') {
				return false;
			}
			//that.unregisterScan();
			let pages = getCurrentPages(); //获取所有页面栈实例列表
			let nowPage = pages[pages.length - 1]; //当前页页面实例
			let prevPage = pages[pages.length - 2]; //上一页页面实例
			if (!that.sumbitFlag) {
				try {
					uni.setStorageSync('product_recpt', that.productList);
				} catch (e) {
					console.log(e.message);
				}
			}
			uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
				delta: 1
			});
			return true;
		},


		methods: {
			initScan() {
				let _this = this;
				main = plus.android.runtimeMainActivity(); //获取activity  
				var IntentFilter = plus.android.importClass('android.content.IntentFilter');
				filter = new IntentFilter();
				filter.addAction("scan.rcv.message"); // 换你的广播动作  
				receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
					onReceive: function(context, intent) {
						plus.android.importClass(intent);
						let code = intent.getByteArrayExtra('barocode');
						let codeStr = utf8ByteToUnicodeStr(code);
						//scanDevice.stopScan();// 停止扫描	
						_this.buttonScan(codeStr);
						_this.viewScan(codeStr);
					}
				});
			},

			//扫描减码
			reduceData() {
				if (this.userflag) {
					this.userflag = false;
				} else {
					this.userflag = true;
				}
			},

			//如果是机器上面的扫描按钮，是增加数据
			buttonScan(codeStr) {
				if (this.userflag) {
					return;
				}
				if (codeStr == null || codeStr == '') {
					this.commonContent = "请扫描数据";
					this.$refs.commonDialog.open();
					return;
				}
				if (!this.popFlag) {
					this.popFlag = true;
				}
				var numReg = /^[0-9]*$/;
				var numRe = new RegExp(numReg)
				this.$refs.alertDialog.open();
				if (codeStr.index("-")) {
					this.allCode = codeStr;
					var arr = allCode.split("-");
					var boxCodeTemp = arr[2] + arr[3];
					for (var j = 0; j < this.productList.length; j++) {
						if (this.productList[j].boxCode == boxCodeTemp) {
							this.content = '物料编码：' + this.code + "\n" + "数量：" + this.codeEqualQty + "\n" + '箱码：' + this
								.boxCode + '\n';
							this.commonContent = codeStr + '此数据已存在';
							this.$refs.commonDialog.open();
							return;
						}
					}
					this.boxCode = boxCodeTemp;
					this.content = '物料编码：' + this.code + "\n" + "数量：" + this.codeEqualQty + "\n" + '箱码：' + this.boxCode +
						'\n';
				} else if (codeStr.index("/")) {
					this.code = codeStr.replace("/", '');
					this.content = '物料编码：' + this.code + "\n" + "数量：" + this.codeEqualQty + "\n" + '箱码：' + this.boxCode +
						'\n';
				} else if (numRe.test(codeStr)) {
					if (codeStr.length > 4) {
						this.code = codeStr;
					} else {
						this.codeEqualQty = codeStr;
					}
					this.content = '物料编码：' + this.code + "\n" + "数量：" + this.codeEqualQty + "\n" + '箱码：' + this.boxCode +
						'\n';
				} else {
					this.commonContent = '请正确扫描条码';
					this.$refs.commonDialog.open();
					return;
				}
			},

			//如果是页面上的减码扫描，那就是删除数据
			viewScan(codeStr) {
				if (!this.userflag) {
					return;
				}
				if (codeStr.index("-")) {
					this.reducePatch = codeStr;
					this.reduceContent = '箱码：' + this.reducePatch + '\n';
					this.$refs.reduceDialog.open();
				} else {
					this.commonContent = '请扫描箱码';
					this.$refs.commonDialog.open();
				}
			},

			submit() {
				var that = this;
				//显示加载框
				uni.showLoading({
					title: "加载中"
				});
				let token = getToken();
				uni.request({
					url: that.baseUrl + '/system/barcode/RT',
					data: {
						orgId: that.orgId,
						productList: that.productList,
						sourceBill: 'MD_ITEM', //单据类型是物料,
						userName: that.userName,
						receiptNot: "WmProductRecpt",
					},
					method: 'POST',
					header: {
						'authorization': token
					},
					dataType: 'json',
					success: (res) => {
						that.sumbitFlag = true;
						var code = res.data.code;
						if (code == '200') {
							var json = JSON.parse(res.data.msg);
							var recptId = json.recptId;
							var codeQty = json.codeQty;
							var date = json.date;
							var msg = '';
							for (var i = 0; i < codeQty.length; i++) {
								var data = codeQty[i];
								msg = msg + data.moDocno + "-" + data.code + "-" + data.codeNum + "箱\n";
							}
							that.makeBarCode(recptId, msg, date);
						} else if (code == '98') {
							var msg = res.data.msg;
							for (var i = 0; i < msg.length; i++) {
								var record = msg[i];
								for (var j = 0; j < that.productList.length; j++) {
									if (record == that.productList[j].boxCode) {
										that.productList[j].flag = true;
									}
								}
							}
							//隐藏加载框
							uni.hideLoading();
							that.commonContent = msg.length + '条数据条码主档已存在，数据已标明，请查看';
							that.$refs.commonDialog.open();
						} else {
							//隐藏加载框
							uni.hideLoading();
							var message = res.data.msg;
							if (message == null || message == '') {
								message = '操作失败';
							}
							that.commonContent = message;
							that.$refs.commonDialog.open();
							return;
						}
					}
				})
			},

			makeBarCode(barcodeContent, msg, date) {
				var ret = printer.initPrinter({});
				printer.printEnableMark({
					enable: true
				});
				printer.setConcentration({ //设置打印浓度。font_level 取值范围：1~39。
					level: 39
				});
				printer.setLineSpacing({
					spacing: 1
				});
				printer.getsupportprint();

				printer.setFontSize({
					fontSize: 5
				});
				printer.setTextBold({
					bold: true
				});
				printer.printBarcode({
					text: 'T' + barcodeContent,
					height: 50,
					barcodeType: 73,
					offset: 1
				});

				printer.printText2({
					offset: 1,
					fontSize: 4,
					isBold: false,
					isUnderLine: false,
					content: date + "\n",
				});
				printer.printText2({
					offset: 1,
					fontSize: 3,
					isBold: false,
					isUnderLine: false,
					content: msg,
				});
				printer.start();
				//隐藏加载框
				uni.hideLoading();
				uni.showToast({
					title: '操作成功',
					icon: 'success',
					duration: 2000
				});
				//that.unregisterScan();
				setTimeout(function() {
					uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
						delta: 1
					});
				}, 2000);
			},

			//开启扫描方法
			registerScan() {
				main.registerReceiver(receiver, filter);
			},

			//关闭扫描方法
			unregisterScan() {
				main.unregisterReceiver(receiver);
			},

			dialogConfirm() {
				console.log(that.allCode)
				//显示加载框
				uni.showLoading({
					title: "加载中"
				});
				//如果三个码都扫描完成
				var that = this;
				if (that.code == null || that.code == '') {
					//隐藏加载框
					uni.hideLoading();
					that.commonContent = '请扫描物料编码';
					that.$refs.commonDialog.open();
					return;
				} else if (that.codeEqualQty == null || that.codeEqualQty == '') {
					//隐藏加载框
					uni.hideLoading();
					that.commonContent = '请扫描数量';
					that.$refs.commonDialog.open();
					return;
				} else if (that.boxCode == null || that.boxCode == '') {
					//隐藏加载框
					uni.hideLoading();
					that.commonContent = '请扫描箱码';
					that.$refs.commonDialog.open();
					return;
				} else {
					console.log(that.allCode)
					uni.request({
						url: that.baseUrl + '/system/barcode',
						data: {
							orgId: that.orgId,
							code: that.code,
							codeEqualQty: that.codeEqualQty,
							boxCode: that.boxCode,
							allCode: that.allCode,
							sourceBill: 'MD_ITEM_SINGLE', //单据类型是物料,
							userName: that.userName,
						},
						method: 'POST',
						header: {
							'authorization': getToken()
						},
						dataType: 'json',
						success: (res) => {
							if (res.data.code == '200') {
								if (that.code != null && that.code != "" && that.codeEqualQty != null && that
									.codeEqualQty != "" && that.boxCode != null && that.boxCode != "") {
									that.productList.push({
										code: that.code,
										codeEqualQty: that.codeEqualQty,
										boxCode: that.boxCode,
										allCode: that.allCode,
										flag: false
									});
								}
								that.code = '';
								that.codeEqualQty = '';
								that.boxCode = '';
								that.allCode = "";
								that.count = '0';
								that.popFlag = false;
								that.$refs.alertDialog.close();
								//隐藏加载框
								uni.hideLoading();
								//that.registerScan();
							} else if (res.data.code == '201') {
								//隐藏加载框
								uni.hideLoading();
								var message = res.data.msg;
								if (message == null || message == "") {
									message = "操作失败";
								}
								that.commonContent = message;
								that.$refs.commonDialog.open();
								//that.registerScan();
							} else if (res.data.ccode == '96') {
								//隐藏加载框
								uni.hideLoading();
								var message = res.data.msg;
								if (message == null || message == "") {
									message = "操作失败";
								}
								that.commonContent = message;
								that.$refs.commonDialog.open();
								//that.registerScan();						
							} else {
								//隐藏加载框
								uni.hideLoading();
								var message = res.data.msg;
								if (message == null || message == "") {
									message = "操作失败";
								}
								that.commonContent = message;
								that.$refs.commonDialog.open();
								that.code = '';
								that.codeEqualQty = '';
								that.boxCode = '';
								that.allCode = "";
								that.count = '0';
								that.popFlag = false;
								that.$refs.alertDialog.close();
							}

						}
					})
				}
			},

			dialogClose() {
				var that = this;
				that.code = '';
				that.codeEqualQty = '';
				that.boxCode = '';
				that.allCode = '';
				that.count = '0';
				that.popFlag = false;
				that.$refs.alertDialog.close();
			},

			reduceConfirm() {
				var that = this;
				var tempList = [];
				for (var i = 0; i < that.productList.length; i++) {
					if (that.productList[i].allCode == that.reducePatch) {

					} else {
						tempList.push(that.productList[i]);
					}
				}
				that.productList = tempList;
				that.$refs.reduceDialog.close();
				that.reduceCode = '';
				that.reduceNumkber = '';
				that.reducePatch = '';
				that.reduceCount = 0;
				that.userflag = false;
			},

			reduceClose() {
				this.reduceCode = '';
				this.reduceNumkber = '';
				this.reducePatch = '';
				this.reduceCount = 0;
				this.userflag = false;
				this.$refs.reduceDialog.close();
			},

			dataConfirm() {
				try {
					const value = uni.getStorageSync('product_recpt');
					this.productList = value;
					uni.removeStorageSync('product_recpt');
					//uniremoveStorageSync('product_recpt_barcode');
				} catch (e) {
					console.log(e.message);
				}
				this.$refs.dataDialog.close();
			},

			dataClose() {
				this.productList = [];
				this.list = [];
				this.barcodeIdList = [];
				try {
					uni.removeStorageSync('product_recpt');
					uni.removeStorageSync('product_recpt_barcode');

				} catch (e) {
					console.log(e.message);
				}
				this.$refs.dataDialog.close();
			},

			messageConfirm() {
				scanDevice.stopScan(); // 停止扫描
				scanDevice.startScan();
				this.$refs.messageDialog.close();
			},

			messageClose() {
				this.userflag = false;
				this.$refs.messageDialog.close();
			},

			commonConfirm() {
				this.commonContent = "";
				this.$refs.commonDialog.close();
			},

			commonClose() {
				this.commonContent = "";
				this.$refs.commonDialog.close();
			}
		}
	}
</script>

<style lang="scss">
	.main {
		background-color: #fff;
		height: 300upx;
		align-items: center;
		margin-top: 10upx;
	}

	.text-content {
		font-size: 48rpx;
		text-align: center;
	}

	.city {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		justify-content: flex-start;
		// width: 160rpx;
		margin-left: 4px;
		font-size: 26rpx;
	}

	.input-view {
		display: flex;
		flex-direction: row;
		flex: 1;
		//background-color: #f8f8f8;
		height: 30px;
		padding: 0 80px;
		flex-wrap: nowrap;
		margin: 7px 0;
		line-height: 30px;
		font-size: 26rpx;
	}

	page {
		width: 100%;
		height: 100%;
	}


	.scrool-page {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
	}

	.header-cont {
		width: 100%;
		height: 110rpx;
		line-height: 100rpx;
		text-align: center;
		// background: red;
	}

	.list-cont {
		flex: 1;
		position: relative;

		.scrool-more {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
		}

		.list {
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #e0e0e0;

		}
	}


	.footer {
		color: #fff;
		line-height: 100rpx;
		flex: 0 0 100rpx;
		/* 不放大不缩小固定100rpx */
	}
</style>